package cn.org.gs.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelDemo {

    public static void main(String[] args) throws Exception {

        int port = 8888;
        ByteBuffer buffer = ByteBuffer.wrap("hello atguigu".getBytes());

        //ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 绑定
        ssc.socket().bind(new InetSocketAddress(port));
        // 设置非阻塞模式
        ssc.configureBlocking(false);
        // 箭筒是否有新的链接进入
        while (true) {
            SocketChannel sc = ssc.accept();
            System.out.println("Waiting for connections");
            if(sc == null) { // 没有监听到链接
                System.out.println("null");
                Thread.sleep(2000);
            } else {
                System.out.println("Incoming connections from " + sc.socket().getRemoteSocketAddress());
                buffer.rewind();
                sc.write(buffer);
                sc.close();
            }
        }
    }
}
